package com.jinjiafeng.framelibrary.banner;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jinjiafeng.framelibrary.R;

import java.lang.reflect.Field;

/**
 * @author jinjiafeng
 *         Time :18-5-26
 */

public class BannerView extends RelativeLayout {
    private static final int GRAVITY_START = -1;
    private static final int GRAVITY_CENTER = 0;
    private static final int GRAVITY_END = 1;
    private BaseBannerAdapter mAdapter;
    private BannerViewPager mBvpViewPager;
    private int mCurrentIndex = 0;
    private LinearLayout mLlIndicatorContainer;
    private TextView mTvBannerTitle;
    private Context mContext;

    /**
     * 指示器大小
     */
    private int mDotSize = 8;
    /**
     * 指示器间距
     */
    private int mDotMargin = 8;
    /**
     * 指示器位置
     */
    private int mDotGravity = GRAVITY_END;
    /**
     * banner 宽高比例
     */
    private float mRatio =16/9f;
    /**
     * 底部颜色
     */
    private int mBottomColor = Color.TRANSPARENT;
    /**
     * 未选中的图片
     */
    private Drawable mNormalDotDrawable;
    /**
     * 已选中的图片
     */
    private Drawable mSelectDotDrawable;
    /**
     * viewpager滑动事件
     */
    private int mScrollTime = 1000;
    /**
     * 自动轮播滚动间隔
     */
    private int mScrollInterval = 3500;

    public BannerView(Context context) {
        this(context, null);
    }

    public BannerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BannerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        inflate(context, R.layout.layout_banner, this);
        initAttributeSet(attrs);
        initView();
    }

    private void initAttributeSet(AttributeSet attrs) {
        final TypedArray array = mContext.obtainStyledAttributes(attrs, R.styleable.BannerView);
        mNormalDotDrawable = array.getDrawable(R.styleable.BannerView_normalDot);
        if (mNormalDotDrawable == null) {
            final int color = array.getColor(R.styleable.BannerView_normalDot, Color.GRAY);
            mNormalDotDrawable = new ColorDrawable(color);
        }

        mSelectDotDrawable = array.getDrawable(R.styleable.BannerView_selectDot);
        if (mSelectDotDrawable == null) {
            final int color = array.getColor(R.styleable.BannerView_selectDot, Color.RED);
            mSelectDotDrawable = new ColorDrawable(color);
        }

        mDotSize = (int) array.getDimension(R.styleable.BannerView_dotSize, dip2px(mDotSize));
        mDotMargin = (int) array.getDimension(R.styleable.BannerView_dotMargin, dip2px(mDotMargin));
        mDotGravity = array.getInt(R.styleable.BannerView_dotGravity, mDotGravity);
        mBottomColor = array.getColor(R.styleable.BannerView_bottomColor, mBottomColor);
        mRatio = array.getFloat(R.styleable.BannerView_ratio, mRatio);
        mScrollTime = array.getInteger(R.styleable.BannerView_scrollTime, mScrollTime);
        mScrollInterval = array.getInteger(R.styleable.BannerView_scrollInterval, mScrollInterval);

        array.recycle();
    }

    private void initView() {
        mBvpViewPager = findViewById(R.id.bvp_banner_pager);
        mTvBannerTitle = findViewById(R.id.tv_banner_title);
        mLlIndicatorContainer = findViewById(R.id.ll_indicator_container);
        //初始化viewpager滑动事件
        initPagerScroll();
        mBvpViewPager.setScrollInterval(mScrollInterval);
        final RelativeLayout.LayoutParams params =
                (LayoutParams) mLlIndicatorContainer.getLayoutParams();
        //设置mLlIndicatorContainer位于RelativeLayout的位置
        params.addRule(getDotGravity());
        RelativeLayout rlBottom = findViewById(R.id.rl_bottom);
        rlBottom.setBackgroundColor(mBottomColor);
    }

    /**
     * 5.把dip转成px
     */
    private int dip2px(int dip) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dip, getResources().getDisplayMetrics());
    }

    private void initPagerScroll() {
        final BannerScroller bannerScroller = new BannerScroller(mContext, new
                AccelerateDecelerateInterpolator());
        bannerScroller.setScrollDuration(mScrollTime);
        try {
            //反射替换viewpager的mScroller,更换setCurrentItem()的过度时间
            final Field field = ViewPager.class.getDeclaredField("mScroller");
            field.set(mBvpViewPager, bannerScroller);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public int getDotGravity() {
        //默认为靠右
        int gravity = ALIGN_PARENT_END;
        switch (mDotGravity) {
            case GRAVITY_START:
                gravity = ALIGN_PARENT_START;
                break;
            case GRAVITY_CENTER:
                gravity = CENTER_IN_PARENT;
                break;
            case GRAVITY_END:
                gravity = ALIGN_PARENT_END;
                break;
            default:
                break;
        }
        return gravity;
    }

    public void setAdapter(BaseBannerAdapter adapter) {
        mAdapter = adapter;
        mBvpViewPager.setAdapter(adapter);
        initIndicator();
        mBvpViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                pageSelect(position);
            }
        });
        final String describeText = mAdapter.describeText(0);
        mTvBannerTitle.setText(describeText);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        getLayoutParams().height = (int) (getWidth() / mRatio);
    }

    private void initIndicator() {
        final int count = mAdapter.getCount();
        mLlIndicatorContainer.removeAllViews();
        for (int index = 0; index < count; index++) {
            final ImageView dotIndicatorView = new DotIndicatorView(mContext);
            LinearLayout.LayoutParams params =
                    new LinearLayout.LayoutParams(mDotSize, mDotSize);

            params.leftMargin = mDotMargin;
            dotIndicatorView.setLayoutParams(params);
            if (index == 0) {
                //设置指示器颜色为选中颜色
                dotIndicatorView.setImageDrawable(mSelectDotDrawable);
            } else {
                dotIndicatorView.setImageDrawable(mNormalDotDrawable);
            }
            mLlIndicatorContainer.addView(dotIndicatorView);
        }
    }

    /**
     * 设置indicator的选中和未选中
     *
     * @param position 第几个位置
     */
    private void pageSelect(int position) {
        // 6.1 把之前亮着的点 设置为默认
        final DotIndicatorView preDot = (DotIndicatorView) mLlIndicatorContainer.getChildAt
                (mCurrentIndex);
        preDot.setImageDrawable(mNormalDotDrawable);
        //将当前页面的点设为点亮
        mCurrentIndex = position % mAdapter.getCount();
        final DotIndicatorView currentDot = (DotIndicatorView) mLlIndicatorContainer.getChildAt
                (mCurrentIndex);
        currentDot.setImageDrawable(mSelectDotDrawable);

        final String describeText = mAdapter.describeText(mCurrentIndex);
        mTvBannerTitle.setText(describeText);
    }
}
